package com.jiejie.service.impl;

import com.jiejie.entity.Movie;
import com.jiejie.service.EsMovieService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class EsMovieServiceImpl implements EsMovieService {
    @Resource
    private ElasticsearchRestTemplate restTemplate;

    @Override
    public List<Movie> getMovieList(String movieName, Integer pageNum) {
        if (pageNum ==null)
            pageNum=1;
        Pageable pageable= PageRequest.of(pageNum-1,20);

        //需要查询的字段
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("movieCname",movieName))
                .should(QueryBuilders.matchQuery("movieEname",movieName));

        //构建高亮查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withHighlightFields(
                        new HighlightBuilder.Field("movieCname"),
                        new HighlightBuilder.Field("movieEname"))
                .withHighlightBuilder(new HighlightBuilder()
                        .preTags("<span style='color:red'>")
                        .postTags("</span>"))
                .build();
        SearchHits<Movie> search=restTemplate.search(searchQuery,Movie.class);
        //得到查询返回的内容
        List<SearchHit<Movie>> searchHits = search.getSearchHits();//getSearchHits();
        List<Movie> movieList=new ArrayList<>();
        for (SearchHit<Movie> searchHit:searchHits) {
            //高亮内容
            Map<String ,List<String>> highlightFields = searchHit.getHighlightFields();

            //将高亮的内容填充到content中
            String highLightCname = highlightFields.get("movieCname") ==null ?searchHit.getContent().getMovieCname():highlightFields.get("movieCname").get(0);

            String highLightEname = highlightFields.get("movieEname") ==null ?searchHit.getContent().getMovieEname():highlightFields.get("movieEname").get(0);
            searchHit.getContent().setMovieCname(highLightCname);
            searchHit.getContent().setMovieEname(highLightEname);

            //放到实体类中
            movieList.add(searchHit.getContent());
        }
        return movieList;
    }
}
